package com.example.demo.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.UnknownHostException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * redis配置类
 *
 * @author jack
 * @data 2021/8/12 3:50 下午
 */
@Configuration
public class RedisConfig {

  @Bean
  @SuppressWarnings("all")
  public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory)
      throws UnknownHostException {
    StringRedisTemplate template = new StringRedisTemplate();
    template.setConnectionFactory(redisConnectionFactory);

    // Json 序列化配置
    Jackson2JsonRedisSerializer<Object> objectJackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(
        Object.class);
    // ObjectMapper 转译
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    objectJackson2JsonRedisSerializer.setObjectMapper(objectMapper);

    // String 的序列化
    StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

    // key 采用String的序列化方式
    template.setKeySerializer(stringRedisSerializer);
    // hash 的key也采用 String 的序列化方式
    template.setHashKeySerializer(stringRedisSerializer);
    // value 序列化方式采用 jackson
    template.setValueSerializer(objectJackson2JsonRedisSerializer);
    // hash 的 value 采用 jackson
    template.setHashValueSerializer(objectJackson2JsonRedisSerializer);
    template.afterPropertiesSet();

    return template;
  }
}
